import wx
import wx.aui
import wx.lib.agw.aui as aui
import wx.lib.agw.flatmenu as FM
from wx.lib.agw.artmanager import ArtManager, RendererBase, DCSaver
from wx.lib.agw.fmresources import ControlFocus, ControlPressed
from wx.lib.agw.fmresources import FM_OPT_SHOW_CUSTOMIZE, FM_OPT_SHOW_TOOLBAR, FM_OPT_MINIBAR

import sqlite3
import os
import time

import list_ctrl_panel
import list_seq_panel
import request_panel
import blast_panel
import db
import db_seq
import controls_panel

from request_panel import EVT_CHANGE_TAB
from blast_panel import EVT_START_BLAST, EVT_START_SEARCH
from list_seq_panel import EVT_START_REQUEST

app_path = "D:\\Eigene Datein\\Python\\TIGS DB\\"
source_path = app_path + "files\\"
image_path = app_path + "images\\"

wildcard = "Excel files (*.csv)|*.csv"


class TestFrame(wx.Frame):

    def __init__(self, parent):
        """Main window. An AUI Manager with AUI Notebooks."""
        wx.Frame.__init__(self, parent, -1, "TIGS DB", size=(1280, 900))
        #self.panel = wx.Panel(self, -1)
        self.CenterOnScreen()
        self._mgr = aui.AuiManager()
        self._mgr.SetManagedWindow(self)

        # Main notebook
        self.main_notebook = aui.AuiNotebook(self)
        self.seq_notebook = aui.AuiNotebook(self)

        # BLAST and search Panel
        self.blastpanel = blast_panel.StartBlast(self.main_notebook)
        self.blastpanel.Bind(EVT_START_BLAST, self.start_blast)
        self.blastpanel.Bind(EVT_START_SEARCH, self.start_search)
        self.blastpanel.search.SetFocus()
        self.main_notebook.AddPage(self.blastpanel, "BLAST and Search", False)
        self._mgr.AddPane(self.main_notebook,
                          aui.AuiPaneInfo().Name("blast").
                          CenterPane().PaneBorder(False))

        # TIGS Panel and Browser
        self.request = request_panel.SqlRequest(self.main_notebook)
        self.request.Bind(EVT_CHANGE_TAB, self.change_selection)
        self.main_notebook.AddPage(self.request, "TIGS Request", False)
        self._mgr.AddPane(self.main_notebook,
                          aui.AuiPaneInfo().Name("tigs").
                          CenterPane().PaneBorder(False))

        self.make_menue()
        self._mgr.Update()

    # ==================================================================================
    # SEARCH
    def start_search(self, evt):
        """Creates a new panel listctrl with the search results."""
        self.seq_data = self.get_search_data()

        listCtrl = list_seq_panel.SequenceListCtrl(self.seq_notebook, self.seq_data)
        listCtrl.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
        listCtrl.Bind(EVT_START_REQUEST, self.start_request)
        self.seq_notebook.AddPage(listCtrl, "Search Results " + str(self.query_text), False)
        self.seq_notebook.SetSelection(int(self.seq_notebook.GetPageCount())-1)

        self._mgr.AddPane(self.seq_notebook,
                          aui.AuiPaneInfo().Name("results").
                         PaneBorder(False).Bottom().MinSize(wx.Size(150, 330)))
        self._mgr.Update()


    def get_search_data(self):
        """Extract data from db_seq from the search term."""
        # Connect to DB
        FILENAME = source_path + "seq_db_09082011.sdb3"
        conn = sqlite3.connect(FILENAME)

        search_text = self.blastpanel.search.GetValue()

        sql = """
            SELECT
            ta_id,
            tube_id,
            corrected_id,
            gabi_phen_id,
            function,
            vector,
            plate,
            position,
            longest_seq,
            primer_left,
            primer_right,
            rnai_seq
            FROM
            SEQUENCE_TABLE
            WHERE ta_id LIKE '%""" + search_text + "%'OR tube_id LIKE '%" + search_text + "%'"

        self.query_text = search_text

        # Get Data
        data = db_seq.get_data_from_db(conn, sql)

        return data

    # ==================================================================================
    # BLAST
    def start_blast(self, evt):
        """Starts BLAST against sequence DB and creates a new listctrl panel."""
        self.seq_data = self.get_blast_data()

        listCtrl = list_seq_panel.SequenceListCtrl(self.seq_notebook, self.seq_data)
        listCtrl.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
        listCtrl.Bind(EVT_START_REQUEST, self.start_request)
        self.seq_notebook.AddPage(listCtrl, "Search Results", False)
        self.seq_notebook.SetSelection(int(self.seq_notebook.GetPageCount())-1)

        self._mgr.AddPane(self.seq_notebook,
                          aui.AuiPaneInfo().Name("results").
                         PaneBorder(False).Bottom().MinSize(wx.Size(150, 330)))
        self._mgr.Update()

    def get_blast_data(self):
        """Extract data from db_seq from the search term."""
        # Connect to DB
        FILENAME = "seq_db_09082011.sdb3"

        conn = sqlite3.connect(FILENAME)

        f_out = open('blast_result.txt', 'r')
        queries = f_out.readlines()

        f_out.close()
        query_sqls = ''
        if queries != []:
            for query in queries:
                query = query.strip()
                query = query.split('\t')
                query_sql = " = '" + str(query[0]) + "'"
                query_sqls = query_sqls + " OR ta_id" + query_sql
            query_sqls = ' WHERE ta_id ' + query_sqls.strip(' OR ta_id ')

            sql = """
                SELECT
                ta_id,
                tube_id,
                corrected_id,
                gabi_phen_id,
                function,
                vector,
                plate,
                position,
                longest_seq,
                primer_left,
                primer_right,
                rnai_seq
                FROM
                SEQUENCE_TABLE""" + query_sqls + " ORDER BY ta_id"


            # Get Data
            data = db_seq.get_data_from_db(conn, sql)
            return data

    # ==================================================================================
    # TIGS REQUEST
    def start_request(self, evt):
        """Creates a new request in TIGS data."""
        # Get request and fill TA-ID Ctrl with it.
        f_hit = open(source_path + 'hit_request.txt', 'r')
        hit = f_hit.read()
        f_hit.close()
        ctrl = self.request.FindWindowById(10)
        ctrl.SetValue(str(hit))
        combo = self.request.FindWindowById(0)
        combo.SetValue("Equals")
        self.main_notebook.SetSelection(1)
        self._mgr.Update()

    def change_selection(self, evt):
        """Creates a new panel with a listctrl and requested TIGS data."""
        self.tigs_data = self.get_tigs_data()
        listCtrl = list_ctrl_panel.ListCtrl(self.main_notebook, self.tigs_data)
        listCtrl.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
        nr = self.main_notebook.GetPageCount()-1
        self.main_notebook.AddPage(listCtrl, "Browse TIGS Data " + str(self.query_text), False)
        self.main_notebook.SetSelection(int(self.main_notebook.GetPageCount())-1)
        self._mgr.Update()


    def get_tigs_data(self):
        """Extract data from TIGS db by user query."""
        # Connect to DB
        FILENAME = source_path + "tigs_db_08082011.sdb3"
        conn = sqlite3.connect(FILENAME)

        # Create DB query.
        f_sql = open(source_path + 'sql_query.txt', 'r')
        queries = f_sql.readlines()
        query_sqls = ''
        if queries != []:
            for query in queries:
                query = query.strip()
                query = query.split('\t')

                # Get query id
                if query[0] == "pIPKTA ID":
                    query_id = "ta_id"
                elif query[0] == "Construct function":
                    query_id = "function"
                elif query[0] == "Gus cells":
                    query_id = "gus_cells"
                elif query[0] == "Haustoria":
                    query_id = "haustoria_amount"
                elif query[0] == "Experiment name":
                    query_id = "experiment_name"
                elif query[0] == "Cultivar name":
                    query_id = "cultivar_name"
                elif query[0] == "Hours after inoculation":
                    query_id = "hours_after_inoculation"
                elif query[0] == "Pathogen name":
                    query_id = "pathogen_name"
                elif query[0] == "Link to excel sheet":
                    query_id = "link_to_excel_sheet"

                # Get query text
                self.query_text = query[2]


                # Get query task
                if query[1] == 'Equals':
                    query_sql = query_id + " = '" + str(self.query_text) + "'"
                elif query[1] == 'Begins with':
                    query_sql = query_id + " LIKE '" + str(self.query_text) + "%'"
                elif query[1] == 'Contains':
                    query_sql = query_id + " LIKE '%" + str(self.query_text) + "%'"

                query_sqls = query_sqls + ' AND ' + query_sql
            query_sqls = 'WHERE ' + query_sqls.strip(' AND ')

        else:
            query_sqls = ""

        sql = """
        SELECT
        ta_id,
        tube_id,
        function,
        gus_cells,
        haustoria_amount,
        experiment_name,
        cultivar_name,
        hours_after_inoculation,
        pathogen_name,
        link_to_excel_sheet
        FROM
        TIGS_Table
        """ + query_sqls + "ORDER BY ta_id"

        # Get Data
        data = db.get_data_from_db(conn, sql)
        return data

    # ==================================================================================
    # Menu
    def make_menue(self):
        # Toolbar
        toolBar = self.CreateToolBar()
        toolBar.AddLabelTool(10, '',
                             wx.Bitmap(image_path + 'export_seq.png'), shortHelp="Export Sequences")
        toolBar.AddLabelTool(20, '',
                             wx.Bitmap(image_path + 'export_tigs.png'), shortHelp="Export TIGS Data")
        toolBar.AddSeparator()
        toolBar.AddLabelTool(30, '',
                             wx.Bitmap(image_path + 'statistics.png'), shortHelp="Start TIGS Statistics")
        #

        # Events
        self.Bind(wx.EVT_TOOL, self.export_sequences, id=10)
        self.Bind(wx.EVT_TOOL, self.export_tigs_results, id=20)
        self.Bind(wx.EVT_TOOL, self.start_statistic, id=30)

        toolBar.Realize()

    def export_sequences(self, evt):
        """Export sequences."""
        dlg = wx.FileDialog(
        self, message="Save file as ...", defaultDir=os.getcwd(),
        defaultFile="", wildcard=wildcard, style=wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            dlg.Destroy()

            f_csv = open(path, 'w')
            lables = ["pIPKTA ID", "Tube ID", "Corrected ID", "GABI Phenom ID",
                      "Construct function", "Vector", "Plate", "Position",
                      "Longest Sequence", "Primer Left", "Primer Right", "RNAi Sequence"]
            for lable in lables:
                f_csv.write(lable + ';')
            f_csv.write('\n')

            if self.seq_data != {}:
                for hit in self.seq_data.iteritems():
                    for seq in hit[1]:
                        f_csv.write(seq + ';')
                    f_csv.write('\n')

            f_csv.close()
            dlg2 = wx.MessageDialog(self, 'Sequences saved',
                           'Saved',
                           wx.OK | wx.ICON_INFORMATION
                           )
            dlg2.ShowModal()
            dlg2.Destroy()

    def export_tigs_results(self, evt):
        """Export TIGS Results."""
        dlg = wx.FileDialog(
        self, message="Save file as ...", defaultDir=os.getcwd(),
        defaultFile="", wildcard=wildcard, style=wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            dlg.Destroy()

            f_csv = open(path, 'w')
            lables = ["pIPKTA ID", "Tube ID", "Construct function", "Gus cells", "Haustoria",
                  "Experiment name", "Cultivar name", "Hours after inoculation",
                  "Pathogen name", "Link to excel sheet"]
            for lable in lables:
                f_csv.write(lable + ';')
            f_csv.write('\n')

            if self.tigs_data != {}:
                for hit in self.tigs_data.iteritems():
                    for seq in hit[1]:
                        f_csv.write(seq + ';')
                    f_csv.write('\n')

            f_csv.close()
            dlg2 = wx.MessageDialog(self, 'TIGS data saved',
                           'Saved',
                           wx.OK | wx.ICON_INFORMATION
                           )
            dlg2.ShowModal()
            dlg2.Destroy()

    def start_statistic(self, evt):
        """Starts TA statistic tool."""
        # Get experiments names:
        experiments = set()
        request_id = set()
        if self.tigs_data != {}:
            for hit in self.tigs_data.itervalues():
                if str(hit[8]) == 'BGH':
                    experiments.add(str(hit[5]))
                    request_id.add(str(hit[0]))
        experiments = sorted(experiments)
        frame = controls_panel.ControlFrame(experiments, request_id)
        frame.Show()

#---------------------------------------------------------------------------
class SketchApp(wx.App):

    def OnInit(self):
        image = wx.Image(image_path + "splash.jpg", wx.BITMAP_TYPE_JPEG)
        bmp = image.ConvertToBitmap()
        wx.SplashScreen(bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
                3500, None, -1)
        wx.Yield()
        time.sleep(5)
        frame = TestFrame(None)
        frame.Show()

        return True

#if __name__ == '__main__':
#    app = wx.PySimpleApp()
#    frame = TestFrame(None)
#    frame.Show(True)
#    app.MainLoop()

if __name__ == "__main__":
    app = SketchApp(False)
    app.MainLoop()